﻿using UnityEngine;
using UnityEditor;
using System.IO;

public class SetBundles : Editor
{
    //场景
    public static string ScenesPath = "Scenes";
    public static string ScenesFullPath = Application.dataPath + "/" + ScenesPath;
    //Shader
    public static string ShadersPath = "Shaders";
    public static string ShadersFullPath = Application.dataPath + "/" + ShadersPath;
    //资源
    public static string ResourcesABDir = "ResourcesAB";
    public const string ASSETS_DIR = "Assets";
    public static string ResourcesABPath = "ResourcesAB";
    public static string ResourcesABFullPath = Application.dataPath + "/" + ResourcesABPath;

    private const string SET_BUNDLE_NAMES = "Assets/ResourceManager/设置Bundle名称";
    private const string SET_ONE_BUNDLE_NAMES = "Assets/ResourceManager/设置选中项的Bundle名称 _F6";
    private const string CHECK_BUNDLE_NAMES = "Assets/ResourceManager/检查Bundle名称";
    private const string COPY_BUNDLE_NAME = "Assets/ResourceManager/复制Bundle名称 _F7";
    private const string COPY_BUNDLE_PATH = "Assets/ResourceManager/复制Bundle路径";
    private const string CANCEL_BUNDLE_NAMES = "Assets/ResourceManager/取消选中项的Bundle名称";
    private const string SET_EFFECT_NAME = "Assets/ResourceManager/设置Common的Bundle名称";
    private const string Check_directory = "Assets/ResourceManager/检查ResourcesAB文件夹";

    //文件路径转为工程内路径
    public static string FilePath2BundlePath(string filePath, string bundleDir)
    {
        string fullPath = Application.dataPath + "/" + bundleDir;
        string bundlePath = Path_Combine(bundleDir, filePath.Substring(fullPath.Length));
        return bundlePath;
    }
    //路径拼接并转换\\->/
    public static string Path_Combine(string path1, string path2)
    {
        path1 = path1.Replace('\\', '/');
        path2 = path2.Replace('\\', '/');
        string result = path1 + "/" + path2;
        result = result.Replace("///", "/");
        result = result.Replace("//", "/");
        return result;
    }


    [MenuItem(SET_BUNDLE_NAMES)]
    public static void SetAssetBundleNames()
    {
        SetResBundleName(ResourcesABFullPath);
        SetSceneBundleName();
        SetShadersBundleName();
        AssetDatabase.Refresh();
        EditorUtility.ClearProgressBar();
    }

    [MenuItem(SET_ONE_BUNDLE_NAMES)]
    public static void SetOneAssetBundleName()
    {
        foreach (var item in Selection.objects)
        {
            string path = AssetDatabase.GetAssetPath(item);
            if (File.GetAttributes(path).CompareTo(FileAttributes.Directory) == 0)
            {
                Debug.LogError("文件夹设置bundle名称失败");
            }
            else
            {
                if (!string.IsNullOrEmpty(path))
                {
                    FileInfo file = new FileInfo(path);
                    if (file.FullName.Contains(ResourcesABPath))
                    {
                        SetOneResBundleName(file);
                    }
                    else if (file.FullName.Contains(ScenesPath))
                    {
                        SetOneSceneBundleName(file);
                    }
                    else
                    {
                        Debug.LogError("设置bundle名称失败");
                    }
                }
            }
        }
        AssetDatabase.Refresh();
    }

    [MenuItem(Check_directory)]
    public static void Check_directorys()
    {
        var dir = new DirectoryInfo(ResourcesABFullPath);
        var dirs = dir.GetDirectories("*", SearchOption.AllDirectories);
        for (var i = 0; i < dirs.Length; ++i)
        {
            string bundlePath = FilePath2BundlePath(dirs[i].FullName, ResourcesABPath);
            string basePath = Path_Combine(ASSETS_DIR, bundlePath);

            var importer = AssetImporter.GetAtPath(basePath);
            if (null != importer)
            {
                if (importer.assetBundleName != string.Empty)
                {
                    //Debug.LogError(dirs[i].FullName);
                    importer.SetAssetBundleNameAndVariant(string.Empty, "");
                }
            }
        }
        AssetDatabase.Refresh();
    }

    //[MenuItem(CHECK_BUNDLE_NAMES)]
    public static void CheckBundles()
    {
        EditorUtility.DisplayProgressBar("检查AssetName中", "正在检查AssetName...", 0f);
        var dir = new DirectoryInfo(Application.dataPath);
        var files = dir.GetFiles("*", SearchOption.AllDirectories);
        for (var i = 0; i < files.Length; ++i)
        {
            var fileInfo = files[i];
            EditorUtility.DisplayProgressBar("检查AssetName中", string.Format("正在检查AssetName...{0}/{1}", i, files.Length), 1f * i / files.Length);
            if (!fileInfo.FullName.EndsWith(".meta", System.StringComparison.OrdinalIgnoreCase) && !fileInfo.Name.EndsWith(".cs", System.StringComparison.OrdinalIgnoreCase))
            {
                string tempStr = fileInfo.FullName.Replace('\\', '/');
                if (!tempStr.Contains(ResourcesABPath))
                {
                    //不在ResourcesAB文件夹          
                    string dPath = tempStr.Substring(Application.dataPath.Length + 1, tempStr.Length - Application.dataPath.Length - 1);
                    var basePath = Path_Combine(ASSETS_DIR, dPath);
                    var importer = AssetImporter.GetAtPath(basePath);
                    if (null != importer)
                    {
                        if (importer.assetBundleName != string.Empty)
                            importer.SetAssetBundleNameAndVariant(string.Empty, "");
                    }
                }
            }
        }
        AssetDatabase.Refresh();
        EditorUtility.ClearProgressBar();
    }


    [MenuItem(CANCEL_BUNDLE_NAMES)]
    public static void CancelBundleName()
    {
        //Object[] objs = Selection.objects;
        Object[] objs = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);

        int count = objs.Length;
        int index = 0;
        foreach (var item in objs)
        {
            var basePath = AssetDatabase.GetAssetOrScenePath(item);

            var importer = AssetImporter.GetAtPath(basePath);
            if (null != importer)
            {
                if (importer.assetBundleName != string.Empty)
                    importer.SetAssetBundleNameAndVariant(string.Empty, "");
            }

            index++;
            EditorUtility.DisplayProgressBar("CancelBundleName", $"Canceling...{index}/{count}", 1f * index / count);
        }
        AssetDatabase.Refresh();
        EditorUtility.ClearProgressBar();
    }


    [MenuItem(SET_EFFECT_NAME)]
    public static void EFFECT_NAME()
    {
        //Object[] objs = Selection.objects;
        Object[] objs = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);

        int count = objs.Length;
        int index = 0;
        foreach (var item in objs)
        {
            var basePath = AssetDatabase.GetAssetOrScenePath(item);
            if ((File.GetAttributes(basePath) & FileAttributes.Directory) != 0)
            {
                continue;
            }
            if (basePath.ToLower().Contains("arts/common"))
            {
                var importer = AssetImporter.GetAtPath(basePath);
                if (null != importer)
                {
                    int lastIdx = basePath.LastIndexOf('/');
                    basePath = basePath.Substring(0, lastIdx);
                    importer.SetAssetBundleNameAndVariant(basePath, "");
                }
            }

            index++;
            EditorUtility.DisplayProgressBar("SET_EFFECT_NAME", $"Set...{index}/{count}", 1f * index / count);
        }
        AssetDatabase.Refresh();
        EditorUtility.ClearProgressBar();
    }


    [MenuItem(COPY_BUNDLE_NAME)]
    public static void CopyBundleName()
    {
        if (null != Selection.objects && Selection.objects.Length == 1)
        {
            string objPath = AssetDatabase.GetAssetPath(Selection.objects[0]);
            var importer = AssetImporter.GetAtPath(objPath);
            if (string.IsNullOrEmpty(importer.assetBundleName))
            {
                Debug.LogError("资源" + objPath + "   bundle名称不存在");
            }
            else
            {
                GUIUtility.systemCopyBuffer = importer.assetBundleName;
                //System.Windows.Forms.Clipboard.SetDataObject(importer.assetBundleName);
            }
        }
    }

    [MenuItem(COPY_BUNDLE_PATH)]
    public static void CopyBundlePath()
    {
        if (null != Selection.objects && Selection.objects.Length == 1)
        {
            string objPath = AssetDatabase.GetAssetPath(Selection.objects[0]);
            if (string.IsNullOrEmpty(objPath))
            {
                Debug.LogError("资源" + objPath + "   bundle路径不存在");
            }
            else
            {
                GUIUtility.systemCopyBuffer = objPath;
                //System.Windows.Forms.Clipboard.SetDataObject(objPath) ;
            }
        }
    }
    public static void SetLuaBundleNames()
    {
        SetResBundleName(ResourcesABFullPath+"/Lua");
        AssetDatabase.Refresh();
        EditorUtility.ClearProgressBar();
    }
    //resources bundle name
    private static void SetResBundleName(string path)
    {
        if (!Directory.Exists(path))
        {
            return;
        }

        EditorUtility.DisplayProgressBar("设置AssetName", "正在设置AssetName中...", 0f);
        var dir = new DirectoryInfo(path);
        //if ((di.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)

        var files = dir.GetFiles("*", SearchOption.AllDirectories);
        for (var i = 0; i < files.Length; ++i)
        {
            SetOneResBundleName(files[i]);
            EditorUtility.DisplayProgressBar("设置AssetName", string.Format("正在设置AssetName中...{0}/{1}", i, files.Length), 1f * i / files.Length);
        }
    }

    public static void SetOneResBundleName(FileInfo fileInfo)
    {
        if (File.GetAttributes(fileInfo.FullName).CompareTo(FileAttributes.Directory) == 0)
        {
            //Debug.LogError("文件夹设置bundle名称失败");
            return;
        }
        if (!fileInfo.Name.EndsWith(".meta", System.StringComparison.OrdinalIgnoreCase)
            && !fileInfo.Name.EndsWith(".cs", System.StringComparison.OrdinalIgnoreCase)
            //&& !fileInfo.Name.EndsWith(".svn-base", System.StringComparison.OrdinalIgnoreCase)
            && fileInfo.FullName.IndexOf(".svn") < 0)
        {
            string bundleName = string.Empty;

            string bundlePath = FilePath2BundlePath(fileInfo.FullName, ResourcesABPath);
            string basePath = Path_Combine(ASSETS_DIR, bundlePath);

            //ResourcesAB下的相对路径
            string relativePath = bundlePath.Substring(ResourcesABPath.Length + 1);

            if (relativePath.StartsWith("Lua/", System.StringComparison.OrdinalIgnoreCase)
                    || relativePath.StartsWith("Spine/", System.StringComparison.OrdinalIgnoreCase)
                    || relativePath.StartsWith("Font/", System.StringComparison.OrdinalIgnoreCase)
                    || relativePath.StartsWith("Fbx/", System.StringComparison.OrdinalIgnoreCase)
                    || relativePath.StartsWith("Texture/", System.StringComparison.OrdinalIgnoreCase))//文件夹打包
            {
                int lastIdx = relativePath.LastIndexOf('/');
                bundleName = relativePath.Substring(0, lastIdx);
            }
            else if (relativePath.StartsWith("Sprite/", System.StringComparison.OrdinalIgnoreCase))
            {
                //文件夹打包
                int idx1 = relativePath.IndexOf('/');
                int idx2 = relativePath.IndexOf('/', idx1 + 1);
                int lastIdx = idx2 == -1 ? idx1 : idx2;
                bundleName = relativePath.Substring(0, lastIdx);
            }
            else
            {
                bundleName = relativePath;
            }

            //拼接ResourcesAB, ResourcesAB 下的资源 bundleName 从 ResourcesAB 开始, 不拼接 Resources
            bundleName = Path_Combine(ResourcesABDir, bundleName);

            var importer = AssetImporter.GetAtPath(basePath);
            if (null != importer)
            {
                if (importer.assetBundleName != bundleName)
                    importer.SetAssetBundleNameAndVariant(bundleName, "");
            }
            else
            {
                Debug.LogError("资源设置出错   " + basePath);
            }
        }
    }
    public static void CopyLua()
    {
        string[] luaPath = new string[] { LuaConst.luaDir, LuaConst.toluaDir, Application.dataPath + "/App/ttddz/Lua" };

        //先删除以前的lua
        string EndPath = Application.dataPath + "/ResourcesAB/Lua";
        DirectoryInfo oldLua = new DirectoryInfo(EndPath);
        if (oldLua.Exists){
            BuildTools.DeleteDirectory(EndPath);
        } 

        foreach (var subPath in luaPath)
        {
            int index = 0;

            var dir = new DirectoryInfo(subPath);
            var files = dir.GetFiles("*.lua", SearchOption.AllDirectories);

            int totalCount = files.Length;
            foreach (var item in files)
            {
                index++;
                EditorUtility.DisplayProgressBar("复制文件中", "进度(" + index.ToString() + "/" + totalCount.ToString() + ")", (float)index / totalCount);
                //Debug.LogError(item.FullName);
                string desPath = item.FullName.Replace(@"\", "/").Replace(subPath, EndPath + "/").Replace(".lua", ".txt");
                
                if(desPath.Contains(".svn")){

                }else{
                    DirectoryTool.CreateDirWithFilePath(desPath);
                    File.Copy(item.FullName, desPath);
                }
                
              
            }
        }

        Debug.Log("CopyLua Finish:");
        EditorUtility.ClearProgressBar();
        AssetDatabase.Refresh();

        //copy pb
        string exedir = string.Empty;
        string currDir = Directory.GetCurrentDirectory();
        string pb_path = Application.dataPath.Replace("Assets", string.Empty) + "\\Proto\\";

        Directory.SetCurrentDirectory(pb_path);
        System.Diagnostics.Process pro = System.Diagnostics.Process.Start(pb_path + "______copy_pb.bat");
        pro.WaitForExit();
        Directory.SetCurrentDirectory(currDir);
    }
    private static void SetSceneBundleName()
    {
        if (!Directory.Exists(ScenesFullPath))
        {
            return;
        }

        EditorUtility.DisplayProgressBar("设置SceneBundleName", "正在设置SceneBundleName...", 0f);
        var dir = new DirectoryInfo(ScenesFullPath);

        var files = dir.GetFiles("*.unity", SearchOption.AllDirectories);
        for (var i = 0; i < files.Length; ++i)
        {
            FileInfo fileInfo = files[i];

            EditorUtility.DisplayProgressBar("设置SceneBundleName", string.Format("正在设置SceneBundleName...{0}/{1}", i, files.Length), 1f * i / files.Length);
            SetOneSceneBundleName(fileInfo);
        }
    }

    private static void SetOneSceneBundleName(FileInfo fileInfo)
    {
        string bundlePath = FilePath2BundlePath(fileInfo.FullName, ScenesPath);
        string basePath = Path_Combine(ASSETS_DIR, bundlePath);

        string bundleName = bundlePath;

        var importer = AssetImporter.GetAtPath(basePath);
        if (null != importer)
        {
            if (importer.assetBundleName != bundleName)
                importer.SetAssetBundleNameAndVariant(bundleName, "");
        }
    }

    //shader bundle
    private static void SetShadersBundleName()
    {
        if (!Directory.Exists(ShadersFullPath))
        {
            return;
        }

        var dir = new DirectoryInfo(ShadersFullPath);
        var files = dir.GetFiles("*", SearchOption.AllDirectories);
        foreach (var fileInfo in files)
        {
            if (!fileInfo.Name.EndsWith(".meta", System.StringComparison.OrdinalIgnoreCase) && !fileInfo.Name.EndsWith(".cs", System.StringComparison.OrdinalIgnoreCase))
            {
                string bundlePath = FilePath2BundlePath(fileInfo.FullName, ShadersPath);
                string basePath = Path_Combine(ASSETS_DIR, bundlePath);

                string bundleName = "shaders.shader";

                var importer = AssetImporter.GetAtPath(basePath);
                if (null != importer)
                {
                    if (importer.assetBundleName != bundleName)
                        importer.SetAssetBundleNameAndVariant(bundleName, "");
                }
                else
                {
                    Debug.LogError("资源设置出错   " + basePath);
                }
            }
        }
    }
}
